package com.lagouedu.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@RefreshScope
public class IpFilter implements GlobalFilter, Ordered {

    @Value("${ipfilter.timeWindow}")
    private Long timeWindow;

    @Value("${ipfilter.times}")
    private Integer times;

    private ConcurrentHashMap<String,Integer> map = new ConcurrentHashMap();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1、调用时，先根据 IP 从 map中获取ip的调用次数
        String hostString = request.getRemoteAddress().getHostString();
        Integer count = map.get(hostString);
        if(count == null){
            map.put(hostString,1);
            // 创建一个定时器 定时清理map中数据
            Timer timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    map.remove(hostString);
                }
            };
            timer.schedule(timerTask, timeWindow);
            // 放行请求
            return chain.filter(exchange);
        }
        if(count>times){
            // 1分钟内访问超过10次则拒绝访问
            String data = "一分钟内访问次数超过限制";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        count++;
        map.put(hostString,count);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
